package com.fdfs.api.core;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fdfs.api.service.FdfsApiService;
import com.fdfs.api.serviceimpl.FdfsApiServiceImpl;


public class MainServer {

	private static final Logger log = LoggerFactory.getLogger(MainServer.class);
	private static final int PORT = 12345;
	private MainServer() {
		
	}
	
	public static void init(String conf_filename) throws FileNotFoundException, IOException, MyException{
		
		ClientGlobal.init(conf_filename);
	}
	
	public static void start(){
		log.info("fastdfs api starting......");
		try {
			TProcessor tprocessor = new FdfsApiService.Processor<FdfsApiService.Iface>(
					new FdfsApiServiceImpl());

			TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket(
					PORT);
			TNonblockingServer.Args tnbArgs = new TNonblockingServer.Args(
					tnbSocketTransport);
			tnbArgs.processor(tprocessor);
			tnbArgs.transportFactory(new TFramedTransport.Factory());
			tnbArgs.protocolFactory(new TCompactProtocol.Factory());

			// 使用非阻塞式IO，服务端和客户端需要指定TFramedTransport数据传输的方式
			TServer server = new TNonblockingServer(tnbArgs);
			log.info("fastdfs api started on port {}",PORT);
			server.serve();

		} catch (Exception e) {
			System.out.println("Server start error!!!");
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		public String conf_filename = "F:\\workspace\\fastdfsapi\\src\\main\\resources\\fdfs_client.conf";

		try {
			if(null == args || args.length == 0){
				throw new Exception("you must put one arg than is config file !");
			}
			MainServer.init(args[0]);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		} 
		MainServer.start();
	}
}
